const canvas = document.getElementById('canvas')
const canvasContainer = document.querySelector('.canvas-container')
const ctx = canvas.getContext('2d')
const audio = document.getElementById('audio')

ctx.imageSmoothingEnabled = true
ctx.imageSmoothingQuality = 'high'

const messageElement = document.querySelector('.message')
const debugPanel = document.querySelector('.debug-panel')
const nameElement = document.querySelector('.name')
const infoElement = document.querySelector('.info')

const List = {
    backImage: 'back.webp',
    backColor: '#666',
    TriangleColor: '#fff',
    progressColor: '#fff',
    nametext: 'Empty - Love',
    infotext: 'Lulleaux / Kid Princess',
    nameColor: '#fff',
    infoColor: '#fff',
    blurAmount: '5px',
    backgroundOpacity: 0.5,  // 添加透明度属性
    useRandomData: false
}

canvas.height = 550
canvas.width = 550
const { width, height } = canvas

let analyser
let dataArray
let randomdata

// 初始化显示
function updateDisplay() {
    // 更新背景
    document.body.style.backgroundColor = List.backColor
    if (List.backImage) {
        document.body.style.backgroundImage = `url('${List.backImage}')`
        document.body.style.backdropFilter = `blur(${List.blurAmount})`
    } else {
        document.body.style.backgroundImage = 'none'
        document.body.style.backdropFilter = 'none'
    }
    // 添加透明度设置
    document.body.style.setProperty('--opacity', List.backgroundOpacity)
    // 更新文本内容和颜色
    nameElement.textContent = List.nametext
    nameElement.style.color = List.nameColor

    infoElement.textContent = List.infotext
    infoElement.style.color = List.infoColor
}

// 添加文件处理函数
function handleFileInputs() {
    // 背景图片处理
    const backImageInput = document.getElementById('backImage')
    backImageInput.addEventListener('change', (e) => {
        const file = e.target.files[0]
        if (file) {
            const reader = new FileReader()
            reader.onload = (e) => {
                List.backImage = e.target.result
                updateDisplay()
            }
            reader.readAsDataURL(file)
        }
    })

    // 音频文件处理
    const audioInput = document.getElementById('audioFile')
    audioInput.addEventListener('change', (e) => {
        const file = e.target.files[0]
        if (file) {
            const url = URL.createObjectURL(file)
            audio.src = url
            // 更新标题为文件名（去除扩展名）
            const fileName = file.name.replace(/\.[^/.]+$/, "")
            List.nametext = fileName
            updateDisplay()

            // 重新初始化音频上下文
            init()
        }
    })

    // 模糊度调节
    const blurInput = document.getElementById('blurAmount')
    const blurValue = document.getElementById('blurValue')
    blurInput.addEventListener('input', (e) => {
        const value = e.target.value + 'px'
        List.blurAmount = value
        blurValue.textContent = value
        updateDisplay()
    })

    // 背景亮度
    const opacityInput = document.getElementById('backgroundOpacity')
    const opacityValue = document.getElementById('opacityValue')
    opacityInput.addEventListener('input', (e) => {
        List.backgroundOpacity = parseFloat(e.target.value)
        opacityValue.textContent = e.target.value
        updateDisplay()
    })

    // 添加随机数据开关处理
    const randomDataToggle = document.getElementById('useRandomData')
    randomDataToggle.checked = List.useRandomData
    randomDataToggle.addEventListener('change', (e) => {
        List.useRandomData = e.target.checked
    })
}

// 初始化调试面板
function initDebugPanel() {
    // 为每个输入框添加事件监听
    Object.keys(List).forEach(key => {
        const input = document.getElementById(key)
        if (input) {
            input.addEventListener('change', (e) => {
                List[key] = e.target.value
                updateDisplay()
            })
        }
    })

    // 添加文件输入处理
    handleFileInputs()
}

window.addEventListener('keydown', (e) => {
    if (e.code === 'Space') {
        if (audio.paused) {
            audio.play()
            draw()
        } else {
            audio.pause()
        }
    }
    if (e.code === 'KeyR') {
        if (messageElement.classList.contains('hide')) {
            messageElement.classList.remove('hide')
        } else {
            messageElement.classList.add('hide')
        }
    }
    if (e.code === 'KeyH') {
        debugPanel.classList.toggle('hide')
    }
})
/**
 * 初始化
 */
function init() {
    const audCtx = new AudioContext()
    const source = audCtx.createMediaElementSource(audio)
    analyser = audCtx.createAnalyser()
    source.connect(analyser)
    analyser.connect(audCtx.destination)
    analyser.fftSize = 64

    // 打乱的是dataArray的索引
    randomdata = Array.from({ length: analyser.frequencyBinCount }, (_, i) => i)
    console.log('randomdata--form', randomdata)

    // 局部小范围打乱（保持趋势）
    randomdata.sort(() => {
        // 控制交换概率（30% 概率发生交换）
        if (Math.random() > 0.6) return 0 // 不交换

        // 交换时，控制交换幅度（±2 范围内）
        return Math.random() - 0.5
    })

    dataArray = new Uint8Array(analyser.frequencyBinCount) // 获取分析数据结果
    console.log('dataArray--', dataArray)
}
init()
initDebugPanel()
updateDisplay()


let currentTime = 0
function draw() {
    // if(audio.paused) return
    requestAnimationFrame(draw)
    ctx.clearRect(0, 0, width, height)
    analyser.getByteFrequencyData(dataArray)

    // 根据开关决定是否使用随机数据
    let bData
    if (List.useRandomData) {
        bData = []
        randomdata.forEach(value => {
            bData.push(dataArray[value])
        })
        console.log('randomdata', bData)

    } else {
        bData = Array.from(dataArray)
        console.log('non-randomdata', bData)

    }

    // 计算等边三角形的基本参数
    const centerX = width / 2
    const centerY = height / 2
    const side = Math.min(width, height) * 0.5
    const mainheight = side * Math.sqrt(3) / 2

    const points = [
        { x: centerX, y: centerY - mainheight * 2 / 3 },
        { x: centerX - side / 2, y: centerY + mainheight * 1 / 3 },
        { x: centerX + side / 2, y: centerY + mainheight * 1 / 3 }
    ]

    // 绘制三角形轮廓
    ctx.lineWidth = 10
    ctx.beginPath()
    ctx.moveTo(points[0].x, points[0].y)
    ctx.lineTo(points[1].x, points[1].y)
    ctx.lineTo(points[2].x, points[2].y)
    ctx.closePath()
    ctx.strokeStyle = List.TriangleColor
    ctx.stroke()

    const barWidth = 6  // 固定矩形宽度
    ctx.fillStyle = List.TriangleColor

    // 左边的矩形
    for (let i = 0; i < bData.length; i++) {
        const value = (bData[i] / 255) * 50  // 标准化高度
        const t = i / bData.length
        const x = points[0].x + (points[1].x - points[0].x) * t
        const y = points[0].y + (points[1].y - points[0].y) * t

        const angle = Math.atan2(points[1].y - points[0].y, points[1].x - points[0].x)

        ctx.save()
        ctx.translate(x, y)
        ctx.rotate(angle)
        ctx.fillRect(-barWidth / 2, 0, barWidth, value)
        ctx.restore()
    }

    // 右边的矩形
    for (let i = 0; i < bData.length; i++) {
        const value = (bData[i] / 255) * 50
        const t = i / bData.length
        const x = points[2].x + (points[0].x - points[2].x) * t
        const y = points[2].y + (points[0].y - points[2].y) * t

        const angle = Math.atan2(points[2].y - points[0].y, points[2].x - points[0].x) + Math.PI

        ctx.save()
        ctx.translate(x, y)
        ctx.rotate(angle)
        ctx.fillRect(-barWidth / 2, 0, barWidth, value)
        ctx.restore()
    }

    // 底边的矩形
    for (let i = 0; i < bData.length; i++) {
        const value = (bData[i] / 255) * 50
        const t = i / bData.length
        const x = points[1].x + (points[2].x - points[1].x) * t
        const y = points[1].y + (points[2].y - points[1].y) * t

        // 底边朝下的角度
        const angle = Math.atan2(points[2].x - points[1].x, points[2].y - points[1].y) - Math.PI / 2

        ctx.save()
        ctx.translate(x, y)
        ctx.rotate(angle)
        ctx.fillRect(-barWidth / 2, 0, barWidth, value)
        ctx.restore()
    }
    // 缩放
    const average = bData.reduce((a, b) => a + b, 0) / bData.length
    const scale = 1 + (average / 64) * 0.2
    canvas.style.transform = `scale(${scale})`

    // 进度条绘制
    currentTime = audio.currentTime
    const duration = audio.duration
    const progress = currentTime / duration

    const progresscenterX = width / 2
    const progresscenterY = height / 2
    const progressside = Math.min(width, height) * 0.5 * progress
    const progressheight = progressside * Math.sqrt(3) / 2

    const progresspoints = [
        { x: progresscenterX, y: progresscenterY - progressheight * 2 / 3 },
        { x: progresscenterX - progressside / 2, y: progresscenterY + progressheight / 3 },
        { x: progresscenterX + progressside / 2, y: progresscenterY + progressheight / 3 }
    ]

    // 绘制三角形轮廓
    ctx.lineWidth = 1
    ctx.beginPath()
    ctx.moveTo(progresspoints[0].x, progresspoints[0].y)
    ctx.lineTo(progresspoints[1].x, progresspoints[1].y)
    ctx.lineTo(progresspoints[2].x, progresspoints[2].y)
    ctx.closePath()
    ctx.fillStyle = List.progressColor
    ctx.fill()
}
draw()